package cn.codeim;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimeServer {
    public void bind(int port){
        //配置服务端NIO线程组
        //这里创建两个NioEventLoopGroup实例，一个用户服务端接受客户端连接，一个用于SocketChannel的读写
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            //ServerBootstrap是用于启动NIO服务端的辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup) //将上面两个group当成参数传入ServerBootstarp
                    .channel(NioServerSocketChannel.class)//设置通道为NioServerSocketChannel
                    .option(ChannelOption.SO_BACKLOG,1024)//配置NioServerSocketChannel的tcp参数
                    .childHandler(new ChildChannelHandler());//绑定实际的事件处理类

            //绑定端口，等待连接
            ChannelFuture channelFuture = b.bind(port).syncUninterruptibly();

            //等待服务器监听关闭
            //使用这个方法进行阻塞，等待服务端链路关闭之后main函数才退出
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //优雅退出，该函数会关闭跟shutdownGracefully相关联的资源
            bossGroup.shutdownGracefully();//关闭线程
            workerGroup.shutdownGracefully();
        }


    }

    //IO事件处理类
    private static class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) {
        int port = 8080;
        if (args!=null && args.length > 0) {
            try{
                port = Integer.parseInt(args[0]);
            }catch (NumberFormatException e){
                System.out.println(e.getMessage());
            }
        }

        new TimeServer().bind(port);
    }
}
